<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.hisiphp.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

namespace app\api\validate;

use app\common\model\User;
use think\facade\Log;
use think\Validate;

/**
 * 注册验证器
 * @package app\api\validate
 */
class RegisterValidate extends Validate
{
    //定义验证规则
    protected $rule = [
        'account|账号'    => 'require|mobile|scenePhone',
        'password|密码'   => 'require|min:8|sceneReg',
        'code|短信验证码'  => 'require|min:6|sceneCode',
    ];

    //定义验证提示
    protected $message = [
        'account.require'       => '手机号不能为空',
        'account.mobile'        => '手机号错误',
        'account.scenePhone'    => '手机号已注册',
        'password.require'      => '密码不能为空',
        'password.min'          => '密码最短8位数',
        'password.sceneReg'     => '密码必须字母加数字',
        'code.sceneCode'        => '短信验证码错误',
    ];


    /**
     *验证手机号
     */
    public function scenePhone($phone)
    {
        $where['username|mobile'] =  $phone;
        $token = User::where($where)->count();
        return !$token;
    }

    /**
     *手机号登录验证码验证
     */
    public function sceneCode($code)
    {
        $account = request()->post('account');
        $redisCode = '';
        try {
            $redisCode = redis()->get('registerCode_' . $account);
            redis()->del('registerCode_' . $account);
            redis()->close();
        } catch (\RedisException $e) {
            Log::info('registerCodeError_'.$e->getMessage());
        }
//        return $code === $redisCode;
        return true;
    }


    public function sceneReg($password){
        $pattern = '/(?=.*[a-zA-Z])(?=.*[0-9])^[a-zA-Z0-9]+$/'; // 定义正则表达式模式，只包含字母和数字
        if (preg_match($pattern, $password)) {
            return true;
        }
        return false;
    }

    /**
     * 验证场景
     */
    protected $scene = [

    ];
}
